package com.code9xs.service.impl;

import com.code9xs.mapper.ArticleMapper;
import com.code9xs.mapper.CommentMapper;
import com.code9xs.mapper.LikeAndFavoritesMapper;
import com.code9xs.mapper.UserMapper;
import com.code9xs.pojo.Article;
import com.code9xs.pojo.Comment;
import com.code9xs.pojo.LikeAndFavorites;
import com.code9xs.pojo.User;
import com.code9xs.service.ArticleService;
import com.code9xs.service.UserService;
import com.code9xs.util.DateUtils;
import com.code9xs.util.PageUtil;
import com.code9xs.util.ReplaceHtml;
import com.code9xs.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author Suhd
 * @date 2021/5/12
 * @time 10:11
 * @wechat i9xswanan
 * @github https://github.com/Code9xs
 */

@Transactional
@Service

public class ArticleServiceImpl implements ArticleService {
    @Autowired
    ArticleMapper articleMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    UserServiceImpl userService;

    @Autowired
    LikeAndFavoritesMapper likeAndFavoritesMapper;

    @Autowired
    CommentMapper commentMapper;

    @Override
    public boolean publishArticle(Article article) {
        int flag = articleMapper.insertSelective(article);
        if (flag > 0){
            return true;
        }
        return false;
    }

    @Override
    public PageUtil getAllArticlePagination(Integer page, Integer pageSize) {
        PageUtil pageUtil = new PageUtil();
        int total = articleMapper.selectAllCount();
        pageUtil.setTotal(total);
        pageUtil.setPageSize(pageSize);
        pageUtil.setPage(page);
        List<Map<String, Object>> mapList = articleMapper.selectArticlePagination(pageUtil.getStartTotal() - 1, pageSize);
        mapList.forEach(v -> {
            User user = userMapper.selectByPrimaryKey((Integer) v.get("uid"));
            v.put("username",user.getUsername());
            v.put("avatar",user.getAvatar());
            v.put("noHtml", ReplaceHtml.getTextFromHtml((String) v.get("text")));
            v.put("time",DateUtils.format((Date) v.get("time"),DateUtils.DATE_TIME_PATTERN));
        });
        pageUtil.setData(mapList);
        return pageUtil;
    }

    @Override
    public Map<String, Object> getUserInfoBar() {
        User currentUser = userService.getCurrentUser();
       Map<String, Object> userInfoBar = articleMapper.selectUserInfoBar(currentUser.getId());
        userInfoBar.put("username",currentUser.getUsername());
        userInfoBar.put("avatar",currentUser.getAvatar());
        userInfoBar.put("id",currentUser.getId());
        return userInfoBar;
    }

    @Override
    public Result getArticleCommentByArticleId(Integer articleId) {
        List<Map<String, Object>> commentList = articleMapper.selectCommentByArticleId(articleId);
        List<Map<String,Object>> delete = new ArrayList<>();
        commentList.forEach(v -> {
            String time = DateUtils.format((Date) v.get("time"), DateUtils.DATE_TIME_PATTERN);
            v.put("time",time);
            Integer id = (Integer)v.get("id");
            List<Object> reply = new ArrayList<>();
            commentList.forEach(i -> {
                Integer precursor = (Integer) i.get("precursor");
                if (precursor == id){
                    i.put("replyName",v.get("username"));
                    delete.add(i);
                    reply.add(i);
                }
            });
            if (!reply.isEmpty()){
                v.put("isReply",true);
            } else {
                 v.put("isReply",false);
            }
            v.put("reply",reply);
        });
        // 删除回复评论
        delete.forEach(v -> {
            commentList.remove(v);
        });
        return Result.succ(HttpServletResponse.SC_OK,"成功",commentList);
    }

    @Override
    public boolean clickLike(Integer articleId) {
        Article article = new Article();
        LikeAndFavorites likeAndFavorites = new LikeAndFavorites();
        likeAndFavorites.setLikes(true);
        likeAndFavorites.setUid(userService.getCurrentUser().getId());
        likeAndFavorites.setArticleId(articleId);
        Integer like = articleMapper.selectByPrimaryKey(articleId).getLikes() + 1;
        article.setLikes(like);
        article.setId(articleId);
        int flagArticle = articleMapper.updateByPrimaryKeySelective(article);
        int flagLike = likeAndFavoritesMapper.isExistUpdateIsNotInsert(articleId, userService.getCurrentUser().getId(), true);
        if (flagArticle > 0 && flagLike > 0){
            return true;
        }
        return false;
    }

    @Override
    public boolean dislike(Integer articleId) {
        Article article = new Article();
        Integer like = articleMapper.selectByPrimaryKey(articleId).getLikes() - 1;
        article.setLikes(like);
        article.setId(articleId);
        articleMapper.updateByPrimaryKeySelective(article);
        likeAndFavoritesMapper.isExistUpdateIsNotInsert(articleId,userService.getCurrentUser().getId(),false);
        return true;
    }

    @Override
    public LikeAndFavorites getUserIsLikeOrFavorites(Integer articleId) {
        LikeAndFavorites likeAndFavorites = likeAndFavoritesMapper.selectUserIsLikeOrFavorites(userService.getCurrentUser().getId(), articleId);
        return likeAndFavorites;
    }

    @Override
    public boolean clickFavorites(Integer articleId) {
        Article article = new Article();
        Integer favorites = articleMapper.selectByPrimaryKey(articleId).getFavorites() + 1;
        article.setFavorites(favorites);
        article.setId(articleId);
        article.setUid(userService.getCurrentUser().getId());
        int flagArticle = articleMapper.updateByPrimaryKeySelective(article);
        int flagFavorites = likeAndFavoritesMapper.isExistUpdateIsNotInsertFavorites(articleId, userService.getCurrentUser().getId(), true);
        if (flagArticle > 0 && flagFavorites > 0){
            return true;
        }
        return false;
    }

    @Override
    public boolean cancelFavorite(Integer articleId) {
        Article article = new Article();
        Integer favorites = articleMapper.selectByPrimaryKey(articleId).getFavorites() - 1;
        article.setFavorites(favorites);
        article.setId(articleId);
        article.setUid(userService.getCurrentUser().getId());
        articleMapper.updateByPrimaryKeySelective(article);
        likeAndFavoritesMapper.isExistUpdateIsNotInsertFavorites(articleId,userService.getCurrentUser().getId(),false);
        return true;
    }

    @Override
    public boolean addViews(Integer articleId) {
        Article article = new Article();
        article.setId(articleId);
        Integer views = articleMapper.selectByPrimaryKey(articleId).getViews() + 1;
        article.setViews(views);
        int flag = articleMapper.updateByPrimaryKeySelective(article);
        if (flag > 0) {
            return true;
        }
        return false;
    }

    @Override
    public Map<String, Object> getArticleItem(Integer articleId) {
        int count = articleMapper.selectCommentCount(articleId);
        Map<String, Object> data = articleMapper.selectArticleItemById(articleId);
        data.put("time",DateUtils.format((Date) data.get("time"),DateUtils.DATE_TIME_PATTERN));
        data.put("comment",count);
        return data;
    }

    @Override
    public boolean publishComment(Integer articleId, String content) {
        Comment comment = new Comment();
        comment.setArticleId(articleId);
        comment.setUid(userService.getCurrentUser().getId());
        comment.setTime(DateUtils.getCurrentTime());
        comment.setContent(content);
        int flag = commentMapper.insertSelective(comment);
        if (flag > 0){
            return true;
        }
        return false;
    }

    @Override
    public boolean publishUserComment(Integer articleId, Integer replyUserId, String content) {
        Comment comment = new Comment();
        comment.setArticleId(articleId);
        comment.setUid(userService.getCurrentUser().getId());
        comment.setTime(DateUtils.getCurrentTime());
        comment.setContent(content);
        comment.setPrecursor(replyUserId);
        int flag = commentMapper.insertSelective(comment);
        if (flag > 0){
            return true;
        }
        return false;
    }

    @Override
    public PageUtil getCurrentUserArticle(Integer page,Integer pageSize) {
        PageUtil pageUtil = new PageUtil();
        User currentUser = userService.getCurrentUser();
        int total = articleMapper.selectArticleCountByUid(currentUser.getId());
        pageUtil.setPage(page);
        pageUtil.setPageSize(pageSize);
        pageUtil.setTotal(total);
        List<Map<String, Object>> articleInfo = articleMapper.selectPaginationUserArticleInfoByUid(currentUser.getId(), pageUtil.getStartTotal() - 1, pageSize);
         articleInfo.forEach(v -> {
             v.put("text",ReplaceHtml.delHTMLTag((String) v.get("text")));
         });
        pageUtil.setData(articleInfo);
        return pageUtil;
    }

    @Override
    public boolean updateArticle(Integer articleId, String content, String title) {
        Article article = new Article();
        article.setId(articleId);
        article.setText(content);
        article.setTime(DateUtils.getCurrentTime());
        article.setTitle(title);
        article.setStatus("已发布");
        final int i = articleMapper.updateByPrimaryKeySelective(article);
        if (i > 0){
            return true;
        }
        return false;
    }

    @Override
    public boolean updateSaveUserArticle(Integer articleId, String content, String title) {
        Article article = new Article();
        article.setId(articleId);
        article.setText(content);
        article.setTitle(title);
        article.setStatus("暂存");
        final int i = articleMapper.updateByPrimaryKeySelective(article);
        if (i > 0){
            return true;
        }
        return false;
    }

    @Override
    public boolean deleteArticle(Integer articleId) {
        final int flag = articleMapper.deleteByPrimaryKey(articleId);
        if (flag > 0){
            return true;
        }
        return false;
    }

    @Override
    public List<Map<String,Object>> getMaxArticle() {
        List<Map<String, Object>> maps = articleMapper.selectMaxArticle();
        maps.forEach(v -> {
            String href = "/all/article/item/" + v.get("id");
            String noHtmlText = ReplaceHtml.delHTMLTag((String) v.get("text"));
            v.put("href",href);
            v.put("noHtmlText",noHtmlText);
        });
        return maps;
    }
}
